package org.forex.impl.engine;

import static org.junit.Assert.assertTrue;

import java.io.IOException;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;

import org.forex.impl.property.MainConfig;
import org.forex.impl.ws.GetInstrumentPrice;
import org.forex.vo.Instrument;
import org.forex.vo.Prices;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.google.gson.Gson;

public class InstrumentChoice {

	private InstrumentTrade insT;
	private Instrument ins;

	private List<Double> buyList;
	private List<Double> noneList;
	private List<Double> sellList;

	@Before
	public void setUp() throws Exception {
		buyList = Arrays
				.asList(1285.300, 1285.300, 1285.31, 1285.315, 1285.317);
		noneList = Arrays.asList(1284.762, 1284.528, 1284.496, 1284.609,
				1284.601);
		sellList = Arrays.asList(1285.301, 1285.300, 1285.300, 1285.299,
				1285.295);
		ins = new Instrument();
		ins.setInstrument("XAU_USD");// oro
	}

	@After
	public void tearDown() throws Exception {
	}

	protected String getTrend(List<Double> l) {

		insT = new InstrumentTrade(ins);

		l.forEach(bl -> {
			Prices pr = new Prices();
			Instrument ins2 = new Instrument();
			ins2.setBid(bl);
			pr.getInstruments().add(ins2);
			insT.addPrice(pr);
		});

		String trend = insT.getTrend();
		System.out.println("Trend: " + trend);
		return trend;
	}

	@Test
	public void choiceTrendBuy() {
		assertTrue(MainConfig.config().trendBuy().equals(getTrend(buyList)));
	}

	@Test
	public void choiceTrendNone() {
		assertTrue(MainConfig.config().trendNone().equals(getTrend(noneList)));
	}

	@Test
	public void choiceRealTrend() throws IOException {

		List<Double> l = new LinkedList<Double>();

		Optional<Prices> prices = null;
		Gson gson = new Gson();
		// take five prices

		int PRICES = 5;

		for (int i = 0; i < PRICES; i++) {

			prices = new GetInstrumentPrice().get(ins.getInstrument());

			prices.ifPresent(p -> {
				l.add(p.getInstruments().get(0).getBid());
			});

			System.out.println(gson.toJson(prices));

			try {
				if (i + 1 != PRICES)
					Thread.sleep(10000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		getTrend(l);
	}

	@Test
	public void choiceTrendSell() {

		assertTrue(MainConfig.config().trendSell().equals(getTrend(sellList)));

	}
	
	@Test
	public void testDoublePrecision(){
		assertTrue(0.0== new InstrumentTrade(null).getDouble(0.0009));
		System.out.println(new InstrumentTrade(null).getDouble(-0.0009));
		assertTrue(0.0== new InstrumentTrade(null).getDouble(-0.0009));
	}
}
